package com.lin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * 处理请求转发逻辑的 Servlet 实现类
 * <p>
 * <strong>路径处理规范:</strong>
 * <ul>
 *   <li>请求转发 ({@link javax.servlet.RequestDispatcher#forward}):
 *     <pre>
 *     // 正确写法（服务器端路径）
 *     req.getRequestDispatcher("/success.jsp").forward(req, resp);
 *     </pre>
 *   </li>
 *   <li>重定向 ({@link HttpServletResponse#sendRedirect}):
 *     <pre>
 *     // 正确写法（客户端路径）
 *     resp.sendRedirect(req.getContextPath() + "/login");
 *     </pre>
 *   </li>
 * </ul>
 *
 * <strong>错误用法警告:</strong>
 * {@code
 * // 错误写法会导致路径重复拼接
 * req.getRequestDispatcher(req.getContextPath() + "/success.jsp")
 * }
 *
 *  避免在 forward() 方法中拼接上下文路径
 * @see <a href="http://localhost:8080/s/login">示例请求路径</a>
 */
public class RequestForwardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取请求参数
        String username = req.getParameter("username");

        String password = req.getParameter("password");

        String[] hobbies = req.getParameterValues("hobbies");

        System.out.println("username: " + username + "\npassword: "
                + password + "\nhobbies: " + Arrays.toString(hobbies));
        if (Objects.equals(username, "admin") && Objects.equals(password, "123")) {
            // 请求转发
            req.getRequestDispatcher("/success.jsp").forward(req, resp);
        } else {
            // 请求转发
            req.getRequestDispatcher("/image").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
